using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{
	
	public partial class FormDbManager : PortalModuleBase
	{
		
#region Controls
		
#endregion
		
#region Web Form Designer Generated Code
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
		}
		
#endregion
		
#region Private Members
		
		private DotNetNuke.Entities.Modules.PortalModuleBase _loaderCtl;
		private FormSettings objFormSettings;
		private string strOperationSuccess;
		private string strInvalidQuery;
		private HtmlTable tableMain;
		private string autoIncField;
		private Code5Systems.FormMaster.Business.FormController objFormCtl;
		private string _foreignKeyFieldName;
		private ModuleInfo modInfo = null;

		#endregion

		#region Data Bind Methods

		private void BindData()
		{
			try
			{
				this.txtConnection.Text = objFormCtl.FormInfo.ExtTableConnStr;
				VerifyConnectionString();
				BindExistingMap();
				this.mvMain.Visible = true;
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
		}
		
		private void CheckThatAllPagesAreMapped()
		{
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
				List<Code5Systems.FormMaster.Business.FormMappingInfo> allMappings = objFormMapCtl.GetByForm(this.objFormCtl.FormInfo.FormID);
				List<int> pagesMapped = ((from m in allMappings select m.PageNum).Distinct()).ToList();
				
				if (pagesMapped.Count > 0 && pagesMapped.Count < objFormCtl.Pages.Count)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, Localization.GetString("NotAllPagesAreMapped", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
			}
			
		}
		
		private void BindPageControls()
		{
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			
			if (objFormMapCtl.GetByForm(objFormCtl.FormInfo.FormID).Where(m => m.PageNum > 1).Count() > 0)
			{
				this.chkExtTableForEachPage.Enabled = false;
			}
			
			this.chkExtTableForEachPage.Checked = objFormCtl.FormInfo.ExtTableForEachPage;
			this.chkExtTableForEachPage.Visible = objFormCtl.Pages.Count > 1;
			
			if (objFormCtl.Pages.Count == 1)
			{
				this.chkExtTableForEachPage.Checked = false;
				if (objFormCtl.FormInfo.ExtTableForEachPage)
				{
					objFormCtl.FormInfo.ExtTableForEachPage = false;
					objFormCtl.Update(objFormCtl.FormInfo);
				}
			}
			
			this.lstFormPage.Visible = this.chkExtTableForEachPage.Visible;
			this.lstFormPage.DataSource = objFormCtl.Pages;
			this.lstFormPage.DataBind();
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				this.lstFormPage.Visible = true;
			}
			else
			{
				this.lstFormPage.Visible = false;
				this.lstFormPage.SelectedIndex = 0;
			}
		}
		
		private void BindExistingMap()
		{
			
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			this.gvExistingMap.EmptyDataText = Localization.GetString("NoMapping", this.LocalResourceFile);
			this.mvMain.Visible = true;
			this.lstCreateAction.SelectedIndex = 0;
			this.mvMain.SetActiveView(this.vExistingMap);
			this.trTableList.Visible = false;
			this.trNewTableName.Visible = false;
			this.cmdSaveConnString.Enabled = true;
			
			SetCurrentPage();
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				CheckThatAllPagesAreMapped();
				this.gvExistingMap.DataSource = objFormMapCtl.GetByPage(this.objFormCtl.FormInfo.FormID, objFormCtl.FormInfo.CurrentPage.PageNum);
				objFormCtl.BindPageDynamicControls(this.rdoFormFields, ModuleId, objFormCtl.FormInfo.CurrentPage.PageNum);
			}
			else
			{
				this.gvExistingMap.DataSource = objFormMapCtl.GetByForm(this.objFormCtl.FormInfo.FormID);
				objFormCtl.BindDynamicControls(this.rdoFormFields, ModuleId);
			}
			
			this.gvExistingMap.DataBind();
			if (this.gvExistingMap.Rows.Count == 0)
			{
				this.cmdCommitOperation.Visible = false;
				this.cmdCancel.Visible = false;
			}
			
			if (objFormCtl.FormInfo.UseExtTable)
			{
				if (objFormCtl.FormInfo.ExtTableForEachPage)
				{
					if (this.gvExistingMap.Rows.Count > 0)
					{
						this.lblCurrentTable.Text = string.Format(Localization.GetString("CurrentTable", this.LocalResourceFile), objFormCtl.FormInfo.CurrentPage.ExtTableName);
						this.lstCreateAction.Enabled = false;
						this.cmdSaveConnString.Enabled = false;
						this.cmdDeleteMappings.Visible = true;
						this.cmdEditMappings.Visible = true;
						
						Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
						
						try
						{
							if (objFormDataCtl.GetFormDataToCopyCount(ModuleId, objFormDataCtl.GetExternalTableIDCsvString(objFormCtl.FormInfo)) > 0)
							{
								this.cmdImportFromXml.Visible = true;
							}
							else
							{
								this.cmdImportFromXml.Visible = false;
							}
							
							if (objFormDataCtl.GetExttableDataToCopyCount(objFormCtl.FormInfo) > 0)
							{
								this.cmdAccessExistingData.Visible = true;
							}
							else
							{
								this.cmdAccessExistingData.Visible = false;
							}
						}
						catch (SqlException sex)
						{
							this.cmdDeleteMappings.Visible = true;
							this.lstCreateAction.Enabled = true;
							this.lblCurrentTable.Text = string.Empty;
							this.cmdEditMappings.Visible = false;
							this.cmdImportFromXml.Visible = false;
							this.cmdAccessExistingData.Visible = false;
							DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, sex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
						}
					}
					else
					{
						this.lstCreateAction.Enabled = true;
						this.lblCurrentTable.Text = string.Empty;
						this.cmdDeleteMappings.Visible = false;
						this.cmdEditMappings.Visible = false;
						this.cmdImportFromXml.Visible = false;
						this.cmdAccessExistingData.Visible = false;
					}
					
				}
				else
				{
					this.lblCurrentTable.Text = string.Format(Localization.GetString("CurrentTable", this.LocalResourceFile), objFormCtl.FormInfo.CurrentPage.ExtTableName);
					this.lstCreateAction.Enabled = false;
					this.cmdSaveConnString.Enabled = false;
					this.cmdDeleteMappings.Visible = true;
					this.cmdEditMappings.Visible = true;
					
					Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
					if (objFormDataCtl.GetFormDataToCopyCount(ModuleId, objFormDataCtl.GetExternalTableIDCsvString(objFormCtl.FormInfo)) > 0)
					{
						this.cmdImportFromXml.Visible = true;
					}
					else
					{
						this.cmdImportFromXml.Visible = false;
					}
					
					if (objFormDataCtl.GetExttableDataToCopyCount(objFormCtl.FormInfo) > 0)
					{
						this.cmdAccessExistingData.Visible = true;
					}
					else
					{
						this.cmdAccessExistingData.Visible = false;
					}
				}
			}
			else
			{
				this.lblCurrentTable.Text = string.Empty;
				this.cmdDeleteMappings.Visible = false;
				this.cmdEditMappings.Visible = false;
				this.cmdImportFromXml.Visible = false;
				this.cmdAccessExistingData.Visible = false;
			}

			this.chkExtTableForEachPage.Enabled = !this.cmdDeleteMappings.Visible;
		}
		
		private void BindTableList()
		{
			this.lstTables.Items.Clear();
			DataTable dt = objFormCtl.GetQueryData(this.txtConnection.Text, "EXEC sp_tables");
			
			//Remove Tables the Core DotNetNuke Tables from the list if using the default connection string
			if (string.IsNullOrEmpty(this.objFormCtl.FormInfo.ExtTableConnStr))
			{
				ListController listCtl = new ListController();
				
				ListEntryInfoCollection oListEntries = listCtl.GetListEntryInfoCollection("FormMasterExtTableMask");
				
				List<string> tableList = new List<string>();
				
				foreach (ListEntryInfo item in oListEntries)
				{
					tableList.Add(item.Value);
				}
				
				for (int i = dt.Rows.Count - 1; i >= 0; i--)
				{
					if (tableList.Contains((dt.Rows[i]["TABLE_NAME"]).ToString()))
					{
						dt.Rows.RemoveAt(i);
					}
				}
			}
			
			dt.DefaultView.RowFilter = "TABLE_TYPE = \'TABLE\'";
			dt.DefaultView.Sort = "TABLE_NAME";
			this.lstTables.DataSource = dt;
			this.lstTables.DataBind();
			
			this.lstTables.Items.Insert(0, new ListItem(Localization.GetString("Select", Utility.GetSharedResourceFile()), "0"));
			
		}
		
		private void BindMapExisting(string tableName)
		{
			
			SetCurrentPage();
			
			ClearGridView(this.gvMappings);
			
			DataSet dsTableInfo = default(DataSet);
			
			dsTableInfo = objFormCtl.ExecuteDataSet(this.txtConnection.Text, "EXEC sp_help [" + tableName + "]");
			
			DataTable identTable = dsTableInfo.Tables[2];
			if (identTable.Rows[0][1] == System.DBNull.Value)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, Localization.GetString("AutoIncrementRequired", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			else
			{
				Session.Add("C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString(), identTable.Rows[0][0]);
				
				if (objFormCtl.FormInfo.ExtTableForEachPage)
				{
					objFormCtl.BindPageDynamicControls(this.rdoFormFields, ModuleId, objFormCtl.FormInfo.CurrentPage.PageNum);
				}
				else
				{
					objFormCtl.BindDynamicControls(this.rdoFormFields, ModuleId);
				}
				
				List<DataRow> delRows = new List<DataRow>();
				foreach (DataRow row in dsTableInfo.Tables[1].Rows)
				{
					if ((row["Computed"]).ToString() == "yes")
					{
						delRows.Add(row);
					}
				}
				
				foreach (DataRow row in delRows)
				{
					dsTableInfo.Tables[1].Rows.Remove(row);
				}
				
				this.gvMappings.DataSource = dsTableInfo.Tables[1];
				this.gvMappings.DataBind();
				this.cmdCommitOperation.Visible = true;
				this.cmdCancel.Visible = true;
				this.mvMain.Visible = true;
				CheckThatAllPagesAreMapped();
			}
			
		}
		
		private void BindFromTable()
		{
			DataSet dsTableInfo = default(DataSet);
			Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			
			dsTableInfo = objFormDataCtl.ExecuteDataSet(this.txtConnection.Text, "EXEC sp_help [" + this.lstTables.SelectedValue + "]");
			
			DataTable identTable = dsTableInfo.Tables[2];
			if (identTable.Rows[0][1] == System.DBNull.Value)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, Localization.GetString("AutoIncrementRequired", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			else
			{
				Session.Add("C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString(), identTable.Rows[0][0]);
				
				this.gvFromTable.DataSource = dsTableInfo.Tables[1];
				
				List<DataRow> delRows = new List<DataRow>();
				foreach (DataRow row in dsTableInfo.Tables[1].Rows)
				{
					if ((row["Computed"]).ToString() == "yes")
					{
						delRows.Add(row);
					}
				}
				
				foreach (DataRow row in delRows)
				{
					dsTableInfo.Tables[1].Rows.Remove(row);
				}
				
				this.gvFromTable.DataBind();
				this.cmdCommitOperation.Visible = true;
				this.cmdCancel.Visible = true;
				this.mvMain.Visible = true;
				CheckThatAllPagesAreMapped();
			}
			
			
		}
		
		private void BindFromFormGrid()
		{
			if (this.chkExtTableForEachPage.Checked)
			{
				objFormCtl.BindPageDynamicControls(this.rdoFormFields, ModuleId, int.Parse(lstFormPage.SelectedValue));
			}
			else
			{
				objFormCtl.BindDynamicControls(this.rdoFormFields, ModuleId, false);
			}
			
			if (this.rdoFormFields.Items.Count == 0)
			{
				this.cmdCommitOperation.Visible = false;
			}
			
			this.gvFromForm.DataSource = this.rdoFormFields.Items;
			this.gvFromForm.DataBind();
			this.gvFromForm.EmptyDataText = Localization.GetString("NoFormFieldData", this.LocalResourceFile);
		}
		
		private void BindImportErrors(List<Code5Systems.FormMaster.Business.ExtTableException> errors)
		{
			this.gvImportErrors.EmptyDataText = Localization.GetString("NoImportErrors", this.LocalResourceFile);
			
			this.gvImportErrors.DataSource = errors;
			this.gvImportErrors.DataBind();
			
		}
		
#endregion
		
#region Private Methods
		
		private void SetCurrentPage()
		{
			if (this.objFormCtl.FormInfo.ExtTableForEachPage)
			{
				objFormCtl.FormInfo.CurrentPage = (from p in objFormCtl.Pages where p.PageNum == int.Parse(this.lstFormPage.SelectedValue) select p).FirstOrDefault();
			}
			else
			{
				objFormCtl.FormInfo.CurrentPage = objFormCtl.Pages[0];
			}
			_foreignKeyFieldName = (string) (objFormCtl.Pages[0].ExtIdentityColumn);
		}
		
		private void MapExistingTable()
		{
			Code5Systems.FormMaster.Business.FormMappingInfo objFormMapInfo = default(Code5Systems.FormMaster.Business.FormMappingInfo);
			ListItem oListItem = default(ListItem);
			List<Code5Systems.FormMaster.Business.FormMappingInfo> mappings = new List<Code5Systems.FormMaster.Business.FormMappingInfo>();
			
			SetCurrentPage();
			
			try
			{
				foreach (GridViewRow row in this.gvMappings.Rows)
				{
					if (row.RowType == DataControlRowType.DataRow)
					{
						if (System.Convert.ToBoolean(string.Compare(row.Cells[6].Text, Localization.GetString("AutoIncrementKey", this.LocalResourceFile), true, Thread.CurrentThread.CurrentCulture)))
						{
							oListItem = this.rdoFormFields.Items.FindByText(row.Cells[6].Text);
							if (oListItem != null)
							{
								objFormMapInfo = new Code5Systems.FormMaster.Business.FormMappingInfo();
								objFormMapInfo.FormField = oListItem.Value;
								objFormMapInfo.FormID = this.objFormCtl.FormInfo.FormID;
								objFormMapInfo.TableField = row.Cells[0].Text;
								objFormMapInfo.DataType = row.Cells[1].Text;
								int temp_result = objFormMapInfo.Length;
								int.TryParse((string) (row.Cells[2].Text), out temp_result);
								objFormMapInfo.Length = temp_result;
								byte temp_result2 = objFormMapInfo.Prec;
								byte.TryParse((string) (row.Cells[3].Text), out temp_result2);
								objFormMapInfo.Prec = temp_result2;
								byte temp_result3 = objFormMapInfo.Scale;
								byte.TryParse((string) (row.Cells[4].Text), out temp_result3);
								objFormMapInfo.Scale = temp_result3;
								objFormMapInfo.Nullable = (row.Cells[5].Text == Localization.GetString("Yes", this.LocalResourceFile)) ? true : false;
								objFormMapInfo.PageNum = objFormCtl.FormInfo.CurrentPage.PageNum;
								mappings.Add(objFormMapInfo);
							}
						}
					}
				}
				
				if (mappings.Count < 1)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, Localization.GetString("FieldsMappedError", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					RevoveIdentityCommandButtons();
				}
				else
				{
					Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
					
					if (objFormCtl.FormInfo.ExtTableForEachPage)
					{
						objFormMapCtl.Add(mappings, objFormCtl.FormInfo.CurrentPage.PageNum);
					}
					else
					{
						objFormMapCtl.Add(mappings);
					}
					
					this.objFormCtl.FormInfo.UseExtTable = true;
					Code5Systems.FormMaster.Business.FormPageController pageCtl = new Code5Systems.FormMaster.Business.FormPageController();
					
					if (this.objFormCtl.FormInfo.ExtTableForEachPage)
					{
						if (this.objFormCtl.FormInfo.CurrentPage != null)
						{
							this.objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = Utility.EncryptString(this.txtConnection.Text);
							this.objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = (string) (Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString());
							this.objFormCtl.FormInfo.CurrentPage.ExtTableName = this.lstTables.SelectedValue;
							pageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
						}
					}
					else
					{
						this.objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = (string) (Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString());
						this.objFormCtl.FormInfo.CurrentPage.ExtTableName = this.lstTables.SelectedValue;
						this.objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = this.txtConnection.Text;
					}
					
					pageCtl.UpdateFormPage(this.objFormCtl.FormInfo.CurrentPage);
					this.objFormCtl.Update(this.objFormCtl.FormInfo);
					
					ResetForm();
				}
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			
			
		}
		
		private bool VerifyFirstPageIsMapped()
		{
			bool pageIsMapped = true;
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
				List<Code5Systems.FormMaster.Business.FormMappingInfo> allMappings = objFormMapCtl.GetByPage(this.objFormCtl.FormInfo.FormID, 1);
				List<int> pagesMapped = ((from m in allMappings select m.PageNum).Distinct()).ToList();
				
				if (objFormCtl.FormInfo.CurrentPage.PageNum != 1 && pagesMapped.Count < 1)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, Localization.GetString("FirstPageMustBeMapped", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
					pageIsMapped = false;
				}
			}
			
			return pageIsMapped;
		}
		
		private void AddC5SLLCDesignTimeScript()
		{
			if (File.Exists(Server.MapPath(this.ControlPath + "assets/js/C5SLLCDesignTime.js")))
			{
				if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), this.GetType().ToString()))
				{
					StreamReader iFile = File.OpenText(Server.MapPath(this.ControlPath + "assets/js/C5SLLCDesignTime.js"));
					string script = iFile.ReadToEnd();
					script = script.Replace("[SCALEERROR]", Localization.GetString("ScaleError", this.LocalResourceFile));
					Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.GetType().ToString(), script, false);
					iFile.Close();
				}
			}
		}
		
		private void CreateTableFromForm()
		{
			Code5Systems.FormMaster.Business.FormMappingInfo oMapInfo = default(Code5Systems.FormMaster.Business.FormMappingInfo);
			List<Code5Systems.FormMaster.Business.FormMappingInfo> fieldList = new List<Code5Systems.FormMaster.Business.FormMappingInfo>();
			
			SetCurrentPage();
			
			foreach (GridViewRow row in this.gvFromForm.Rows)
			{
				
				CheckBox chkIgnore = (CheckBox) (row.Cells[5].FindControl("chkIgnore"));
				if (chkIgnore != null)
				{
					if (chkIgnore.Checked)
					{
						continue;
					}
				}
				
				oMapInfo = new Code5Systems.FormMaster.Business.FormMappingInfo();
				oMapInfo.PageNum = objFormCtl.FormInfo.CurrentPage.PageNum;
				
				ListItem oListItem = this.rdoFormFields.Items.FindByText(row.Cells[0].Text);
				if (oListItem != null)
				{
					oMapInfo.FormField = oListItem.Value;
					oMapInfo.TableField = oListItem.Text;
				}
				
				DropDownList lstDataType = (DropDownList) (row.Cells[1].FindControl("lstDataType"));
				if (lstDataType != null)
				{
					oMapInfo.DataType = lstDataType.SelectedValue;
				}
				
				TextBox txtLength = (TextBox) (row.Cells[2].FindControl("txtLength"));
				if (txtLength != null)
				{
					if (string.IsNullOrEmpty(txtLength.Text))
					{
						HiddenField hidden = (System.Web.UI.WebControls.HiddenField) (row.Cells[2].FindControl("hidden"));
						if (hidden != null)
						{
							oMapInfo.Length = int.Parse(hidden.Value);
						}
					}
					else
					{
						oMapInfo.Length = int.Parse(txtLength.Text);
					}
				}
				
				if (oMapInfo.DataType == "numeric" || oMapInfo.DataType == "decimal")
				{
					DropDownList lstPrec = (DropDownList) (row.Cells[3].FindControl("lstPrec"));
					if (lstDataType != null)
					{
						oMapInfo.Prec = byte.Parse(lstPrec.SelectedValue);
					}
					
					DropDownList lstScale = (DropDownList) (row.Cells[4].FindControl("lstScale"));
					if (lstDataType != null)
					{
						oMapInfo.Scale = byte.Parse(lstScale.SelectedValue);
					}
				}
				
				CheckBox chkNullable = (CheckBox) (row.Cells[5].FindControl("chkNullable"));
				if (chkNullable != null)
				{
					oMapInfo.Nullable = chkNullable.Checked;
				}
				
				oMapInfo.FormID = objFormCtl.FormInfo.FormID;
				
				fieldList.Add(oMapInfo);
			}
			
			string strKeyFieldName = Utility.GetValidControlID(this.txtNewTableName.Text);
			StringBuilder sbCreate = new StringBuilder();
			string tableName = string.Format("{0}{1}", Code5Systems.FormMaster.Data.DataProvider.Instance().ObjectQualifier, this.txtNewTableName.Text);
			sbCreate.Append(string.Format("CREATE TABLE [{0}] ({1}", tableName, Environment.NewLine));
			sbCreate.Append(string.Format("[{0}ID] [int] IDENTITY(1,1) NOT NULL,{1}", strKeyFieldName, Environment.NewLine));
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				if (objFormCtl.FormInfo.CurrentPage.PageNum > 1)
				{
					sbCreate.Append(string.Format("[{0}] [int] NOT NULL,{1}", objFormCtl.Pages[0].ExtIdentityColumn, Environment.NewLine));
				}
			}
			
			Code5Systems.FormMaster.Business.FormMappingInfo map = default(Code5Systems.FormMaster.Business.FormMappingInfo);
			for (int index = 0; index <= fieldList.Count - 1; index++)
			{
				map = fieldList[index];
				sbCreate.Append("[" + map.TableField + "] " + map.DataType + " ");
				switch (map.DataType)
				{
					case "nvarchar":
					case "varchar":
					case "nchar":
					case "char":
						sbCreate.Append("(" + map.Length.ToString() + ") ");
						break;
					case "decimal":
					case "numeric":
						sbCreate.Append("(" + map.Prec + "," + map.Scale + ") ");
						break;
				}
				if (map.Nullable)
				{
					sbCreate.Append("NULL");
				}
				else
				{
					sbCreate.Append("NOT NULL");
				}
				if (index < fieldList.Count - 1)
				{
					sbCreate.Append("," + Environment.NewLine);
				}
			}
			
			sbCreate.Append(")" + Environment.NewLine + Environment.NewLine);
			
			
			sbCreate.Append(string.Format("ALTER TABLE [{0}] WITH NOCHECK ADD{1}", tableName, Environment.NewLine));
			sbCreate.Append(string.Format("CONSTRAINT [{0}PK_{1}] PRIMARY KEY  CLUSTERED{2}", Code5Systems.FormMaster.Data.DataProvider.Instance().ObjectQualifier, strKeyFieldName, Environment.NewLine));
			sbCreate.Append(string.Format("( [{0}ID] ASC )", strKeyFieldName));
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				if (objFormCtl.FormInfo.CurrentPage.PageNum > 1)
				{
					sbCreate.Append(Environment.NewLine + Environment.NewLine);
					sbCreate.Append(string.Format("ALTER TABLE {0} WITH NOCHECK ADD CONSTRAINT [{1}_{2}_FK{3}] FOREIGN KEY([{4}]) REFERENCES [{5}] ([{6}])", tableName, objFormCtl.Pages[0].ExtTableName, tableName, objFormCtl.FormInfo.CurrentPage.PageNum, objFormCtl.Pages[0].ExtIdentityColumn, objFormCtl.Pages[0].ExtTableName, objFormCtl.Pages[0].ExtIdentityColumn));
				}
			}
			
			string ddl = sbCreate.ToString();
			
			objFormCtl.FormInfo.UseExtTable = true;
			
			Code5Systems.FormMaster.Business.FormPageController pageCtl = new Code5Systems.FormMaster.Business.FormPageController();

			string extTableName = String.Empty;

			if (this.lstTables.Visible)
			{
				extTableName = this.lstTables.Text;
			}
			else
			{
				extTableName = this.txtNewTableName.Text;
			}

			if (this.objFormCtl.FormInfo.ExtTableForEachPage)
			{
				if (objFormCtl.FormInfo.CurrentPage != null)
				{
					objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = Utility.EncryptString(this.txtConnection.Text);
					objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = strKeyFieldName + "ID";
					objFormCtl.FormInfo.CurrentPage.ExtTableName = extTableName;
					pageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
				}
			}
			else
			{
				this.objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = strKeyFieldName + "ID";
				this.objFormCtl.FormInfo.CurrentPage.ExtTableName = extTableName;
				objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = this.txtConnection.Text;
				pageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
			}
			
			Code5Systems.FormMaster.Business.FormMappingController objMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			
			objMapCtl.CreateTableFromForm(sbCreate.ToString(), fieldList, objFormCtl, this.ModuleId);
			
			ResetForm();
			
		}
		
		private void CreateFormFromTable()
		{
			Code5Systems.FormMaster.Business.FormMappingInfo oMapInfo = default(Code5Systems.FormMaster.Business.FormMappingInfo);
			List<Code5Systems.FormMaster.Business.FormMappingInfo> fieldList = new List<Code5Systems.FormMaster.Business.FormMappingInfo>();
			GridViewRow row = default(GridViewRow);
			Code5Systems.FormMaster.Business.FormPageController oPageCtl = new Code5Systems.FormMaster.Business.FormPageController();
			XDocument xDoc = default(XDocument);
			
			Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo = null;
			
			SetCurrentPage();
			
			oPageCtl.ResetPage(objFormCtl.FormInfo.CurrentPage);
			xDoc = XDocument.Parse(objFormCtl.FormInfo.CurrentPage.PageData);
			oPageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
			
			//objFormCtl.ResetForm(xDoc)
			//objFormCtl.UpdateFormDefinition(ModuleId, xDoc.ToString(), UserId)
			//objFormCtl.FormInfo.TableColumns = 1
			//objFormCtl.FormInfo.TableRows = Me.gvFromTable.Rows.Count - 1
			int rowAdder = 1;

			for (int index = 0; index <= this.gvFromTable.Rows.Count - 1; index++)
			{
				row = this.gvFromTable.Rows[index];

				if (row.Cells[0].Text == Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString())
				{
					rowAdder = 0;
					continue;
				}
				
				oMapInfo = new Code5Systems.FormMaster.Business.FormMappingInfo();
				oMapInfo.PageNum = objFormCtl.FormInfo.CurrentPage.PageNum;
				oMapInfo.FormID = objFormCtl.FormInfo.FormID;
				oMapInfo.TableField = row.Cells[0].Text;
				oMapInfo.DataType = row.Cells[1].Text;
				oMapInfo.Length = int.Parse(row.Cells[2].Text);
					
				byte temp_result = oMapInfo.Prec;
				byte.TryParse((string) (row.Cells[3].Text), out temp_result);
				oMapInfo.Prec = temp_result;
					
				byte temp_result2 = oMapInfo.Scale;
				byte.TryParse(row.Cells[4].Text, out temp_result2);
				oMapInfo.Scale = temp_result2;
					
				if (row.Cells[5].Text == Localization.GetString("Yes", this.LocalResourceFile))
				{
					oMapInfo.Nullable = true;
				}
				else
				{
					oMapInfo.Nullable = false;
				}
					
				DropDownList lstType = (DropDownList) (row.Cells[6].FindControl("lstType"));
				if (lstType != null)
				{
					objFormControlInfo = objFormCtl.AddControl(xDoc, int.Parse(lstType.SelectedValue).ToEnum<ControlType>(), (index + rowAdder).ToString(), "1");
				}

				if (objFormControlInfo != null)
				{
					oMapInfo.FormField = objFormControlInfo.ID;
					objFormControlInfo.CssClass = "NormalTextBox";

					TextBox txtFieldName = (TextBox)(row.Cells[7].FindControl("txtFieldName"));
					if (txtFieldName != null)
					{
						objFormControlInfo.FieldName = (string)(Utility.GetValidDbFieldName(txtFieldName.Text).Trim());
						objFormControlInfo.Label = txtFieldName.Text;
					}

					objFormControlInfo.LabelCssClass = "SubHead";

					if (objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.CheckBox)
					{
						CheckBox chkRequired = (CheckBox)(row.Cells[8].FindControl("chkRequired"));
						if (chkRequired != null)
						{
							objFormControlInfo.Required = chkRequired.Checked;
							if (objFormControlInfo.Required)
							{
								Code5Systems.FormMaster.Business.FormControlInfo objCurValidatorControlInfo = objFormCtl.AddValidatorControl(xDoc, objFormControlInfo, Code5Systems.FormMaster.Business.ControlType.RequiredFieldValidator);
							}
						}
					}

				}
					
				objFormCtl.UpdateControlValues(xDoc, objFormControlInfo);
					
				fieldList.Add(oMapInfo);
					
				objFormCtl.FormInfo.CurrentPage.TableRows = (byte) index;
					
			}
			
			objFormCtl.FormInfo.UseExtTable = true;
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				objFormCtl.FormInfo.CurrentPage.ExtTableName = this.lstTables.SelectedItem.Text;
				objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = (string) (Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString());
				objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = this.txtConnection.Text;
				objFormCtl.FormInfo.CurrentPage.PageData = xDoc.ToString();
				oPageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
			}
			else
			{
				objFormCtl.FormInfo.CurrentPage.ExtTableName = this.lstTables.SelectedItem.Text;
				objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn = (string) (Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString());
				objFormCtl.FormInfo.CurrentPage.ExtTableConnStr = this.txtConnection.Text;
				objFormCtl.FormInfo.CurrentPage.PageData = xDoc.ToString();
				oPageCtl.UpdateFormPage(objFormCtl.FormInfo.CurrentPage);
				
				objFormCtl.FormInfo.ExtTableName = this.lstTables.SelectedItem.Text;
				objFormCtl.FormInfo.ExtIdentityColumn = (string) (Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString());
				objFormCtl.FormInfo.ExtTableConnStr = this.txtConnection.Text;
			}
			
			//objFormCtl.UpdateFormDefinition(ModuleId, xDoc.ToString(), UserId)
			objFormCtl.Update(objFormCtl.FormInfo);
			
			Code5Systems.FormMaster.Business.FormMappingController objMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			objMapCtl.Add(fieldList, objFormCtl.FormInfo.CurrentPage.PageNum);
			
			ResetForm();
			
		}
		
		private bool VerifyConnectionString()
		{
			bool isValid = true;
			//Verify the Connection String
			DataTable dt = objFormCtl.GetQueryData(this.txtConnection.Text, "Select newid()");
			if (dt.Columns["Results"] != null)
			{
				isValid = false;
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, (dt.Rows[0]["Results"]).ToString(), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			
			return isValid;
		}
		
		private void ClearGridView(GridView gview)
		{
			for (int rowIndex = gview.Rows.Count - 1; rowIndex >= 0; rowIndex--)
			{
				gview.DeleteRow(rowIndex);
			}
			gview.DataBind();
		}
		
		private void ResetForm()
		{
			//Hide everything and start with a new page
			this.cmdCommitOperation.Visible = false;
			this.cmdCommitMappings.Visible = false;
			this.cmdCancel.Visible = false;
			this.mvMain.Visible = false;
			this.mvMain.SetActiveView(this.vExistingMap);
			this.trTableList.Visible = false;
			this.trNewTableName.Visible = false;
			this.lstCreateAction.SelectedIndex = 0;
			this.cmdSaveConnString.Enabled = true;
			this.lstCreateAction.Enabled = true;
			
			if (!this.chkExtTableForEachPage.Checked)
			{
				this.lstFormPage.SelectedIndex = 0;
			}
			
			BindExistingMap();
		}
		
		private void RevoveIdentityCommandButtons()
		{
			//Remove the Commands Buttons for the Identity Column
			foreach (GridViewRow row in this.gvMappings.Rows)
			{
				if (row.Cells[0].Text == this.objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn)
				{
					row.Cells[7].Controls.Clear();
					row.Cells[8].Controls.Clear();
					break;
				}
			}
		}
		
#endregion
		
#region Event Handlers
		
		protected void Page_Load(System.Object sender, System.EventArgs e)
		{
			try
			{
				this.LoaderCtl = (PortalModuleBase)this.Parent.Parent;

				ModuleController modCtl = new ModuleController();
				modInfo = modCtl.GetModule(this.LoaderCtl.ModuleId);

				UserController objUsers = new UserController();
				UserInfo objUser = UserController.GetCurrentUserInfo();

				if (!(objUser.IsSuperUser || DotNetNuke.Security.PortalSecurity.IsInRole("Administrators")))
				{
					if (!DotNetNuke.Security.Permissions.ModulePermissionController.HasModuleAccess(DotNetNuke.Security.SecurityAccessLevel.Edit, "edit", modInfo))
						Response.Redirect("~/" + DotNetNuke.Common.Globals.glbDefaultPage);
				}
				
				objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
				
				AddC5SLLCDesignTimeScript();
				
				//Check it External Table Deny List has been Created
				//This is here for Form Master Upgrades.
				ListController listCtl = new ListController();
				ListInfo oListInfo = listCtl.GetListInfo("FormMasterExtTableMask");
				if (oListInfo == null)
				{
					objFormCtl.CreateExtTableMaskList(FMGlobals.MaskTables);
				}
				else
				{
					ListEntryInfoCollection list = listCtl.GetListEntryInfoCollection("FormMasterExtTableMask");
					bool bIsNewList = false;
					foreach (ListEntryInfo item in list)
					{
						if (item.Text == "Dashboard_Controls")
						{
							bIsNewList = true;
							break;
						}
					}
					if (!bIsNewList)
					{
						objFormCtl.CreateExtTableMaskList(FMGlobals.MaskTablesDNN5_2);
					}
				}
				
				Utility.LocalizeGridView(this.gvMappings, this.LocalResourceFile);
				Utility.LocalizeGridView(this.gvFromForm, this.LocalResourceFile);
				Utility.LocalizeGridView(this.gvFromTable, this.LocalResourceFile);
				Utility.LocalizeGridView(this.gvImportErrors, this.LocalResourceFile);
				Utility.LocalizeGridView(this.gvExistingMap, this.LocalResourceFile);
				
				this.cmdDeleteMappings.OnClientClick = "if(!confirm(\'" + Localization.GetString("DeleteMappings", LocalResourceFile) + "\')) return ";
				
				strOperationSuccess = Localization.GetString("OperationSuccess", this.LocalResourceFile);
				
				//this.lblHeading.Text = Localization.GetString("Heading", this.LocalResourceFile);
				
				objFormSettings = Utility.GetFormSettings(ModuleId);
				
				if (!Page.IsPostBack)
				{
					BindPageControls();
					SetCurrentPage();
					BindData();
				}
				else
				{
					SetCurrentPage();
				}
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}
		
		protected void chkIgnore_CheckChanged(System.Object sender, System.EventArgs e)
		{
			CheckBox chkIgnore = default(CheckBox);
			BaseValidator valBase = default(BaseValidator);
			foreach (GridViewRow row in this.gvFromForm.Rows)
			{
				chkIgnore = (CheckBox) (row.Cells[6].FindControl("chkIgnore"));
				if (chkIgnore != null)
				{
					if (chkIgnore.Checked)
					{
						valBase = (BaseValidator) (row.Cells[1].FindControl("rfvDataType"));
						if (valBase != null)
						{
							valBase.Enabled = !chkIgnore.Checked;
						}
						valBase = (BaseValidator) (row.Cells[1].FindControl("rfvLength"));
						if (valBase != null)
						{
							valBase.Enabled = !chkIgnore.Checked;
						}
					}
				}
				
			}
		}
		
		protected void lstTables_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			switch (this.lstCreateAction.SelectedValue)
			{
				case "0":
					break;
				case "1":
					this.cmdCommitOperation.Visible = false;
					this.cmdCancel.Visible = false;
					this.mvMain.Visible = false;
					BindMapExisting(this.lstTables.SelectedValue);
					break;
					
				case "2":
					break;
				case "3":
					this.cmdCommitOperation.Visible = false;
					this.cmdCancel.Visible = false;
					this.mvMain.Visible = false;
					BindFromTable();
					break;
					
			}
			
		}

		protected void gvMappings_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
		{
			
			try
			{
				GridViewRow row = ((GridView) e.CommandSource).Rows[int.Parse((e.CommandArgument).ToString())];
				if (e.CommandName == "Select")
				{
					Page.Validate("Mappings");
					if (!Page.IsValid)
					{
						return;
					}
					row.Cells[6].Text = this.rdoFormFields.SelectedItem.Text;
					row.Cells[7].Enabled = false;
					row.Cells[8].Enabled = true;
					
					this.rdoFormFields.SelectedItem.Enabled = false;
					this.rdoFormFields.SelectedIndex = -1;
				}
				else
				{
					this.rdoFormFields.Items.FindByText(row.Cells[6].Text).Enabled = true;
					
					row.Cells[6].Text = string.Empty;
					row.Cells[7].Enabled = true;
					row.Cells[8].Enabled = false;
					
					this.rdoFormFields.SelectedIndex = -1;
				}
				
				RevoveIdentityCommandButtons();
				
				this.gvMappings.SelectedIndex = -1;
				
				this.rfvFormFields.Enabled = false;
				foreach (ListItem item in this.rdoFormFields.Items)
				{
					if (item.Enabled)
					{
						this.rfvFormFields.Enabled = true;
					}
				}
				CheckThatAllPagesAreMapped();
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			
			
		}

		protected void gvMappings_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			if (e.Row.RowIndex == -1)
			{
				return;
			}
			
			if (e.Row.Cells[0].Text == Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString())
			{
				e.Row.Cells[6].Text = Localization.GetString("AutoIncrementKey", this.LocalResourceFile);
				e.Row.Cells[7].Controls.Clear();
				e.Row.Cells[8].Controls.Clear();
			}
			
			if (e.Row.Cells[0].Text == _foreignKeyFieldName)
			{
				e.Row.Cells[6].Text = Localization.GetString("ForeignKey", this.LocalResourceFile);
				e.Row.Cells[7].Controls.Clear();
				e.Row.Cells[8].Controls.Clear();
			}
			
			//For all the "n" type columns sp_help reports the full size representation, need to
			//cut in half to avoid user confusion
			if (e.Row.Cells[1].Text.StartsWith("n"))
			{
				int fieldLength = default(int);
				int.TryParse((string) (e.Row.Cells[2].Text), out fieldLength);
				if (fieldLength > 1)
				{
					fieldLength = (int) (fieldLength / 2);
					e.Row.Cells[2].Text = fieldLength.ToString();
				}
			}
			
		}

		protected void gvMappings_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
		{
			e.Cancel = false;
		}

		protected void gvImportErrors_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
		{
			try
			{
				if (e.CommandName == "Delete")
				{
					int formDataID = default(int);
					if (int.TryParse((e.CommandArgument).ToString(), out formDataID))
					{
						Code5Systems.FormMaster.Business.FormDataController oDataCtrl = new Code5Systems.FormMaster.Business.FormDataController();
						oDataCtrl.Delete(ModuleId, formDataID, objFormCtl.FormInfo);
						
						if (Session["ImportErrors"] != null)
						{
							List<Code5Systems.FormMaster.Business.ExtTableException> errors = default(List<Code5Systems.FormMaster.Business.ExtTableException>);
							errors = (List<Code5Systems.FormMaster.Business.ExtTableException>) (Session["ImportErrors"]);
							foreach (Code5Systems.FormMaster.Business.ExtTableException item in errors)
							{
								if (item.FormDataID == formDataID)
								{
									errors.Remove(item);
									BindImportErrors(errors);
									break;
								}
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			
		}

		protected void gvImportErrors_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			if (e.Row.RowIndex == -1)
			{
				return;
			}
			
			LinkButton cmdDeleteErrorData = (LinkButton) (e.Row.Cells[2].FindControl("cmdDeleteErrorData"));
			if (cmdDeleteErrorData != null)
			{
				cmdDeleteErrorData.OnClientClick = GetDeleteMsg;
			}
		}

		protected void gvImportErrors_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
		{
			e.Cancel = false;
		}
		
		protected void lstCreateAction_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			
			this.cmdCommitOperation.Visible = false;
			this.cmdCancel.Visible = false;
			this.mvMain.Visible = false;
			SetCurrentPage();
			
			switch (this.lstCreateAction.SelectedValue)
			{
				case "0":
					this.mvMain.SetActiveView(this.vExistingMap);
					this.trTableList.Visible = false;
					this.trNewTableName.Visible = false;
					this.cmdSaveConnString.Enabled = true;
					break;
					
				case "1":
					if (!VerifyFirstPageIsMapped())
					{
						this.lstCreateAction.SelectedIndex = 0;
						this.mvMain.SetActiveView(this.vExistingMap);
						return;
					}
					this.mvMain.SetActiveView(this.vMapExisting);
					this.trTableList.Visible = true;
					this.trNewTableName.Visible = false;
					BindTableList();
					ClearGridView(this.gvMappings);
					this.rdoFormFields.Items.Clear();
					this.cmdSaveConnString.Enabled = false;
					break;
					
				case "2":
					if (!VerifyFirstPageIsMapped())
					{
						this.lstCreateAction.SelectedIndex = 0;
						this.mvMain.SetActiveView(this.vExistingMap);
						return;
					}
					this.mvMain.SetActiveView(this.vFromForm);
					this.trTableList.Visible = false;
					this.trNewTableName.Visible = true;
					this.txtNewTableName.Text = string.Empty;
					this.cmdCommitOperation.Visible = true;
					this.cmdCancel.Visible = true;
					this.mvMain.Visible = true;
					this.cmdSaveConnString.Enabled = false;
					BindFromFormGrid();
					break;
					
				case "3":
					if (!VerifyFirstPageIsMapped())
					{
						this.lstCreateAction.SelectedIndex = 0;
						this.mvMain.SetActiveView(this.vExistingMap);
						return;
					}
					this.mvMain.SetActiveView(this.vFromTable);
					this.trTableList.Visible = true;
					this.trNewTableName.Visible = false;
					ClearGridView(this.gvFromTable);
					this.cmdSaveConnString.Enabled = false;
					BindTableList();
					break;
			}
			CheckThatAllPagesAreMapped();
		}
		
		protected void cmdSaveConnString_Click(System.Object sender, System.EventArgs e)
		{
			
			try
			{
				ResetForm();
				
				//Verify the Connection String
				if (VerifyConnectionString())
				{
					Code5Systems.FormMaster.Business.FormInfo objFormInfo = objFormCtl.FormInfo;
					objFormCtl.FormInfo.ExtTableConnStr = this.txtConnection.Text;
					objFormCtl.Update(objFormInfo);
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, strOperationSuccess, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
				}
				
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			
		}
		
		protected void cmdCommitOperation_Click(System.Object sender, System.EventArgs e)
		{
			
			switch (this.lstCreateAction.SelectedValue)
			{
				case "0": //View Existing Mappings
					break;
				case "1": //Map Existing Table
					MapExistingTable();
					break;
				case "2": //Create Table from Form
					Page.Validate("FromForm");
					if (!Page.IsValid)
					{
						return ;
					}
					CreateTableFromForm();
					break;
				case "3": //Create Form from Table
					CreateFormFromTable();
					break;
			}
		}

		protected void gvFromTable_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			
			if (e.Row.RowIndex == -1)
			{
				return;
			}
			
			if (e.Row.Cells[0].Text == Session["C5SLLCAutoIncrementField_" + objFormCtl.FormInfo.FormID.ToString()].ToString())
			{
				WebControl oValidator = (WebControl) (e.Row.Cells[3].FindControl("rfvFieldName"));
				if (oValidator != null)
				{
					oValidator.Enabled = false;
				}
				
				DropDownList lstType = (DropDownList) (e.Row.Cells[7].FindControl("lstType"));
				if (lstType != null)
				{
					lstType.Enabled = false;
				}
				
				TextBox txtFieldName = (TextBox) (e.Row.Cells[7].FindControl("txtFieldName"));
				if (txtFieldName != null)
				{
					txtFieldName.Enabled = false;
				}
				
				CheckBox chkRequired = (CheckBox) (e.Row.Cells[8].FindControl("chkRequired"));
				if (chkRequired != null)
				{
					chkRequired.Visible = false;
				}
				
			}
			else
			{
				TextBox txtFieldName = (TextBox) (e.Row.Cells[7].FindControl("txtFieldName"));
				if (txtFieldName != null)
				{
					txtFieldName.Text = e.Row.Cells[0].Text;
				}
			}
			
			//For all the "n" type columns sp_help reports the full size representation, need to
			//cut in half to avoid user confusion
			if (e.Row.Cells[1].Text.StartsWith("n"))
			{
				int fieldLength = default(int);
				int.TryParse((string) (e.Row.Cells[2].Text), out fieldLength);
				if (fieldLength > 1)
				{
					fieldLength = (int) (fieldLength / 2);
					e.Row.Cells[2].Text = fieldLength.ToString();
				}
			}
			
		}

		protected void gvFromTable_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
		{
			e.Cancel = false;
		}
		
		protected void gvExistingMap_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				
				//Replace the Control ID with the Field Label
				ListItem oListItem = this.rdoFormFields.Items.FindByValue(e.Row.Cells[6].Text);
				if (oListItem != null)
				{
					e.Row.Cells[6].Text = oListItem.Text;
				}
				
				//Make Null Prec of 0
				if (e.Row.Cells[3].Text == "0")
				{
					e.Row.Cells[3].Text = string.Empty;
				}
				
				//Make null Scale of 0
				if (e.Row.Cells[4].Text == "0")
				{
					e.Row.Cells[4].Text = string.Empty;
				}
				
				//Change True/False to Yes/No
				if (e.Row.Cells[5].Text == "True")
				{
					e.Row.Cells[5].Text = Localization.GetString("Yes", this.LocalResourceFile);
				}
				else
				{
					e.Row.Cells[5].Text = Localization.GetString("No", this.LocalResourceFile);
					
				}
			}
		}
		
		protected void cmdDeleteMappings_Click(System.Object sender, System.EventArgs e)
		{
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			Code5Systems.FormMaster.Business.FormDataController oFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			
			SetCurrentPage();
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				objFormMapCtl.DeleteByPage(this.objFormCtl.FormInfo.FormID, objFormCtl.FormInfo.CurrentPage.PageNum);
				oFormDataCtl.SetPageExtTableIdNull(objFormCtl.FormInfo.FormID, objFormCtl.FormInfo.CurrentPage.PageNum);
				List<Code5Systems.FormMaster.Business.FormMappingInfo> mappings = objFormMapCtl.GetByForm(objFormCtl.FormInfo.FormID);
				if (mappings.Count == 0)
				{
					this.objFormCtl.FormInfo.ExtTableForEachPage = false;
					this.objFormCtl.FormInfo.UseExtTable = false;
					this.objFormCtl.Update(this.objFormCtl.FormInfo);
				}
			}
			else
			{
				objFormMapCtl.Delete(this.objFormCtl.FormInfo.FormID);
				oFormDataCtl.SetExtTableIdNull(ModuleId);
				this.objFormCtl.FormInfo.UseExtTable = false;
				this.objFormCtl.Update(this.objFormCtl.FormInfo);
			}
			
			ResetForm();
		}
		
		protected void cmdEditMappings_Click(System.Object sender, System.EventArgs e)
		{
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			List<Code5Systems.FormMaster.Business.FormMappingInfo> alMappings = default(List<Code5Systems.FormMaster.Business.FormMappingInfo>);
			
			SetCurrentPage();
			
			if (objFormCtl.FormInfo.ExtTableForEachPage)
			{
				alMappings = objFormMapCtl.GetByPage(this.objFormCtl.FormInfo.FormID, objFormCtl.FormInfo.CurrentPage.PageNum);
			}
			else
			{
				alMappings = objFormMapCtl.GetByForm(this.objFormCtl.FormInfo.FormID);
			}
			
			Dictionary<string, Code5Systems.FormMaster.Business.FormMappingInfo> oMapDict = new Dictionary<string, Code5Systems.FormMaster.Business.FormMappingInfo>();
			
			this.mvMain.SetActiveView(this.vMapExisting);
			this.trTableList.Visible = true;
			this.trNewTableName.Visible = false;
			this.cmdImportFromXml.Visible = false;
			this.cmdAccessExistingData.Visible = false;
			BindTableList();
			ClearGridView(this.gvMappings);
			this.rdoFormFields.Items.Clear();
			
			this.cmdCancel.Visible = false;
			this.mvMain.Visible = false;
			BindMapExisting(this.objFormCtl.FormInfo.CurrentPage.ExtTableName);

			this.cmdCommitOperation.Visible = false;
			this.cmdCommitMappings.Visible = true;
			
			foreach (Code5Systems.FormMaster.Business.FormMappingInfo mapping in alMappings)
			{
				oMapDict.Add(mapping.TableField, mapping);
			}
			
			foreach (GridViewRow row in this.gvMappings.Rows)
			{
				if (oMapDict.ContainsKey(row.Cells[0].Text))
				{
					Code5Systems.FormMaster.Business.FormMappingInfo oMapping = oMapDict[row.Cells[0].Text];
					
					ListItem oListItem = this.rdoFormFields.Items.FindByValue(oMapping.FormField);
					if (oListItem != null)
					{
						row.Cells[6].Text = oListItem.Text;
						row.Cells[7].Enabled = false;
						row.Cells[8].Enabled = true;
						oListItem.Enabled = false;
					}
				}
			}
			
			this.lstTables.SelectedIndex = this.lstTables.Items.IndexOf(this.lstTables.Items.FindByValue(this.objFormCtl.FormInfo.CurrentPage.ExtTableName));
			
			this.lstCreateAction.SelectedIndex = 1;
			
		}

		protected void gvFromForm_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			
			e.Row.Cells[0].Text = e.Row.Cells[0].Text;
			
			DropDownList lstDataType = (DropDownList) (e.Row.Cells[1].FindControl("lstDataType"));
			if (lstDataType != null)
			{
				TextBox txtLength = (TextBox) (e.Row.Cells[2].FindControl("txtLength"));
				HiddenField hidden = (System.Web.UI.WebControls.HiddenField) (e.Row.Cells[2].FindControl("hidden"));
				if (txtLength != null)
				{
					lstDataType.Attributes.Add("onchange", " C5SLLC_SetDataTypeLen(this,\'" + txtLength.ClientID + "\',\'" + hidden.ClientID + "\');");
				}
			}
			
			DropDownList lstPrec = (DropDownList) (e.Row.Cells[3].FindControl("lstPrec"));
			if (lstPrec != null)
			{
				for (short index = 1; index <= 38; index++)
				{
					lstPrec.Items.Add(index.ToString());
				}
				lstPrec.SelectedIndex = 17;
			}
			
			DropDownList lstScale = (DropDownList) (e.Row.Cells[3].FindControl("lstScale"));
			if (lstScale != null)
			{
				for (short index = 0; index <= 38; index++)
				{
					lstScale.Items.Add(index.ToString());
				}
				lstScale.SelectedIndex = 0;
				
				if (lstPrec != null)
				{
					lstScale.Attributes.Add("onchange", "C5SLLC_CheckMaxScale(this,\'" + lstPrec.ClientID + "\');");
					
				}
			}
		}
		
		protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			ResetForm();
		}
		
		protected void cmdImportFromXml_Click(System.Object sender, System.EventArgs e)
		{
			List<Code5Systems.FormMaster.Business.FormMappingInfo> mappings = default(List<Code5Systems.FormMaster.Business.FormMappingInfo>);
			Code5Systems.FormMaster.Business.DataTransferInfo oDTInfo = new Code5Systems.FormMaster.Business.DataTransferInfo();
			Code5Systems.FormMaster.Business.DataTransferInfo oTempDTInfo = default(Code5Systems.FormMaster.Business.DataTransferInfo);
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			Code5Systems.FormMaster.Business.FormDataController objDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			Code5Systems.FormMaster.Business.ExtTableException localEx = default(Code5Systems.FormMaster.Business.ExtTableException);
			
			Session.Remove("ImportErrors");
			
			this.mvMain.SetActiveView(this.vDataTransferResults);
			
			cmdImportFromXml.Visible = false;
			this.mvMain.Visible = true;
			
			objFormCtl.BindDynamicControls(this.rdoFormFields, ModuleId);
			
			foreach (Code5Systems.FormMaster.Business.FormPageInfo oPage in objFormCtl.Pages)
			{
				objFormCtl.FormInfo.CurrentPage = oPage;
				mappings = objFormMapCtl.GetByPage(this.objFormCtl.FormInfo.FormID, objFormCtl.FormInfo.CurrentPage.PageNum);
				
				foreach (Code5Systems.FormMaster.Business.FormMappingInfo mapInfo in mappings)
				{
					ListItem oListItem = this.rdoFormFields.Items.FindByValue(mapInfo.FormField);
					if (oListItem != null)
					{
						mapInfo.FormFieldLabel = oListItem.Text;
					}
				}
				
				oTempDTInfo = objDataCtl.CopyDataFromXmlStore(objFormCtl, this.ControlPath, mappings);
				oDTInfo.ExtTableName += oTempDTInfo.ExtTableName + ", ";
				oDTInfo.TotalRows = oTempDTInfo.TotalRows;
				oDTInfo.SuccessRows = oTempDTInfo.SuccessRows;
				oDTInfo.FailedRows = oTempDTInfo.FailedRows;
				foreach (Code5Systems.FormMaster.Business.ExtTableException ex in oTempDTInfo.ExceptionList)
				{
					localEx = ex;
					if (!oDTInfo.ExceptionList.Exists(g => g.FormDataID == localEx.FormDataID))
					{
						oDTInfo.ExceptionList.Add(ex);
					}
				}
			}
			
			this.lblExtTableName.Text = oDTInfo.ExtTableName;
			this.lblTotalRows.Text = (oDTInfo.TotalRows).ToString();
			this.lblSuccessRows.Text = (oDTInfo.SuccessRows).ToString();
			this.lblFailedRows.Text = (oDTInfo.FailedRows).ToString();
			
			if (Session["ImportErrors"] == null)
			{
				Session.Add("ImportErrors", oDTInfo.ExceptionList);
			}
			
			SetCurrentPage();
			
			BindImportErrors(oDTInfo.ExceptionList);
			
		}
		
		protected void cmdAccessExistingData_Click(object sender, EventArgs e)
		{
			Code5Systems.FormMaster.Business.FormDataController objDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			
			Session.Remove("ExtTableAccessErrors");
			
			this.mvMain.SetActiveView(this.vDataTransferResults);
			
			this.cmdAccessExistingData.Visible = false;
			
			Code5Systems.FormMaster.Business.DataTransferInfo oDTInfo = objDataCtl.AttachExtTableData(objFormCtl.FormInfo, UserId);
			this.lblExtTableName.Text = oDTInfo.ExtTableName;
			this.lblTotalRows.Text = (oDTInfo.TotalRows).ToString();
			this.lblSuccessRows.Text = (oDTInfo.SuccessRows).ToString();
			this.lblFailedRows.Text = (oDTInfo.FailedRows).ToString();
			
			if (Session["ExtTableAccessErrors"] == null)
			{
				Session.Add("ExtTableAccessErrors", oDTInfo.ExceptionList);
			}
			
			BindImportErrors(oDTInfo.ExceptionList);
		}
		
		protected void cmdImportContinue_Click(System.Object sender, System.EventArgs e)
		{
			Session.Remove("ImportErrors");
			Session.Remove("ExtTableAccessErrors");
			ResetForm();
		}
		
		protected void chkExtTableForEachPage_CheckedChanged(object sender, EventArgs e)
		{
			objFormCtl.FormInfo.ExtTableForEachPage = this.chkExtTableForEachPage.Checked;
			objFormCtl.Update(objFormCtl.FormInfo);
			this.lstFormPage.SelectedIndex = 0;
			BindPageControls();
		}

		protected void lstFormPage_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			BindExistingMap();
		}

		protected void cmdCommitMappings_Click(object sender, EventArgs e)
		{
			Code5Systems.FormMaster.Business.FormMappingInfo oMapInfo = default(Code5Systems.FormMaster.Business.FormMappingInfo);
			List<Code5Systems.FormMaster.Business.FormMappingInfo> fieldList = new List<Code5Systems.FormMaster.Business.FormMappingInfo>();
			ListItem oListItem;

			SetCurrentPage();
			foreach (GridViewRow row in this.gvMappings.Rows)
			{
				// The Foreign Key Column
				if (row.Cells[0].Text == this.objFormCtl.FormInfo.CurrentPage.ExtIdentityColumn)
				{
					continue;
				}

				oMapInfo = new Code5Systems.FormMaster.Business.FormMappingInfo();
				oMapInfo.PageNum = objFormCtl.FormInfo.CurrentPage.PageNum;

				oMapInfo.TableField = row.Cells[0].Text;
				oMapInfo.DataType = row.Cells[1].Text;

				oListItem = this.rdoFormFields.Items.FindByText(row.Cells[6].Text);
				if (oListItem != null)
				{
					oMapInfo.FormField = oListItem.Value;
				}
				else
				{
					// An UnMapped Column
					continue;
				}

				string length = row.Cells[2].Text;
				if (!String.IsNullOrWhiteSpace(length))
				{
					if (string.IsNullOrEmpty(length))
					{
						HiddenField hidden = (System.Web.UI.WebControls.HiddenField)(row.Cells[2].FindControl("hidden"));
						if (hidden != null)
						{
							oMapInfo.Length = int.Parse(hidden.Value);
						}
					}
					else
					{
						oMapInfo.Length = int.Parse(length);
					}
				}

				if (oMapInfo.DataType == "numeric" || oMapInfo.DataType == "decimal")
				{
					string prec = row.Cells[3].Text;
					if (!String.IsNullOrWhiteSpace(oMapInfo.DataType))
					{
						oMapInfo.Prec = byte.Parse(prec);
					}

					string lstScale = row.Cells[4].Text;
					if (!String.IsNullOrWhiteSpace(oMapInfo.DataType))
					{
						oMapInfo.Scale = byte.Parse(lstScale);
					}
				}

				string nullable = row.Cells[5].Text;
				if (!String.IsNullOrWhiteSpace(nullable))
				{
					if(nullable.ToLower() == "yes")
						oMapInfo.Nullable = true;
					else
						oMapInfo.Nullable = false;
				}

				oMapInfo.FormID = objFormCtl.FormInfo.FormID;

				fieldList.Add(oMapInfo);
			}

			Code5Systems.FormMaster.Business.FormMappingController objMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
			objMapCtl.Add(fieldList);
			ResetForm();
		}
		
#endregion
		
#region Public Properties
		public PortalModuleBase LoaderCtl
		{
			get
			{
				if (_loaderCtl == null)
				{
					_loaderCtl = this;
				}
				
				return _loaderCtl;
			}
			set
			{
				_loaderCtl = value;
			}
		}
		
		public string GetDeleteMsg
		{
			get
			{
				return string.Format("return confirm(\'{0}\');", Localization.GetString("DeleteItem", this.LocalResourceFile));
			}
		}
#endregion

	}
	
}


